package priv.abadstring.study.rocketmq.javaapi.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

public class SyncProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("haoke");
        producer.setNamesrvAddr("abadstring.me:9876");
        producer.start();

        for (int i = 0; i < 10; i++) {
            Message msg = new Message(
                    "song-song" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );

            // 消息队列选择器
            MessageQueueSelector selector = new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object args) {
                    int index = ((Integer) args) % list.size();
                    return list.get(index);
                }
            };

            // 第三个参数 1001 是订单号之类的 ID
            // 将传入到 MessageQueueSelector.select 的 args 参数
            // 相同 ID 的 消息会被依次放入同一个队列中
            SendResult sendResult = producer.send(msg, selector, 1001);

            System.out.printf("%s%n", sendResult);
        }

        producer.shutdown();
    }
}
